import 'package:flutter/material.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';
import 'date_time_picker.dart';

class AddMoodRecordDialog extends StatefulWidget {
  final String babyId;
  const AddMoodRecordDialog({Key? key, required this.babyId}) : super(key: key);

  @override
  State<AddMoodRecordDialog> createState() => _AddMoodRecordDialogState();
}

class _AddMoodRecordDialogState extends State<AddMoodRecordDialog> {
  final _formKey = GlobalKey<FormState>();
  DateTime _date = DateTime.now();
  String _mood = '开心';
  final _descriptionController = TextEditingController();

  final Map<String, IconData> _moodIcons = {
    '开心': Icons.sentiment_very_satisfied,
    '平静': Icons.sentiment_satisfied,
    '疲倦': Icons.sentiment_neutral,
    '烦躁': Icons.sentiment_dissatisfied,
    '哭闹': Icons.sentiment_very_dissatisfied,
  };

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('添加心情记录'),
      content: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            DateTimeFormField(
              label: '记录时间',
              value: _date,
              onChanged: (value) => setState(() => _date = value),
              validator: (value) => value == null ? '请选择时间' : null,
            ),
            const SizedBox(height: 16),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children:
                  _moodIcons.entries.map((entry) {
                    final isSelected = _mood == entry.key;
                    return InkWell(
                      onTap: () => setState(() => _mood = entry.key),
                      child: Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color:
                              isSelected
                                  ? Theme.of(
                                    context,
                                  ).colorScheme.primary.withOpacity(0.1)
                                  : null,
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          entry.value,
                          color:
                              isSelected
                                  ? Theme.of(context).colorScheme.primary
                                  : Colors.grey,
                          size: 32,
                        ),
                      ),
                    );
                  }).toList(),
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _descriptionController,
              decoration: const InputDecoration(labelText: '描述'),
              maxLines: 3,
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(onPressed: _submit, child: const Text('保存')),
      ],
    );
  }

  void _submit() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.mood,
          timestamp: _date,
          data: {'mood': _mood, 'description': _descriptionController.text},
        ),
      );
      if (mounted) Navigator.pop(context);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
      }
    }
  }

  @override
  void dispose() {
    _descriptionController.dispose();
    super.dispose();
  }
}
